package com.oman.metadata;

import java.lang.ref.WeakReference;

import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

class FrameTask extends AsyncTask<Integer, Void, Bitmap> {
    private static String TAG = "FrameTask";
    private final MediaMetadataRetriever mediaMetadataRetriever;
    private Integer mPosition;
    private int mTotalDuration;


//    private VideoViewInfo mVideoInfo;
    private final WeakReference<ImageView> imageViewReference;

    public FrameTask(ImageView imageView,MediaMetadataRetriever mRetriever ) {
        imageViewReference = new WeakReference<ImageView>(imageView);
        mediaMetadataRetriever = mRetriever;

        String duration = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        try {
            mTotalDuration = Integer.parseInt(duration);
        } catch (NumberFormatException e) {
            Log.w(TAG, "Integer.parseInt() NumberFormatException");
        }
    }

    @Override
    protected void onPreExecute() {
        Log.d(TAG, "onPreExecute");
        super.onPreExecute();
    }

    @Override
    protected Bitmap doInBackground(Integer... params) {
        Log.d(TAG, "doInBackground");

        mPosition = params[0];
        int rate = (mPosition * mTotalDuration)/100;
        Bitmap bmFrame = mediaMetadataRetriever.getFrameAtTime(rate * 1000); // unit in microsecond
//       Bitmap bmFrame = mediaMetadataRetriever.getFrameAtTime(rate * 1000, MediaMetadataRetriever.OPTION_CLOSEST);
       return bmFrame;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        Log.d(TAG, "onProgressUpdate");
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        Log.d(TAG, "onPostExecute");
        if(this.isCancelled()) {
            bitmap = null;
        }
        if(imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if(imageView != null) {
                imageView.setImageBitmap(bitmap);
            }
        }
    }

    @Override
    protected void onCancelled() {
        Log.d(TAG, "onCancelled");
        super.onCancelled();
    }

}
